﻿using ConsoleTables;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils;

namespace Service.Impl
{
    public class IpServiceImpl : BaseServiceImpl<string, object>, IpService
    {
        public string Ip()
        {
            // 判断是否有参数
            if(this.CommandContext.InputCommandParams.Count > 0)
            {
                string ip = this.CommandContext.InputCommandParams["ip"];
                int netmask = 24;
                if (this.CommandContext.InputCommandParams.ContainsKey("netmask")) netmask = int.Parse(this.CommandContext.InputCommandParams["netmask"]);
                string gateway = "";
                if (this.CommandContext.InputCommandParams.ContainsKey("gateway")) gateway = this.CommandContext.InputCommandParams["gateway"];
                
                return setIp(ip, netmask, gateway);
            }
            else
            {
                return showIp();
            }
        }
        /// <summary>
        /// 设置ip信息
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="netmask"></param>
        /// <param name="gateway"></param>
        /// <returns></returns>
        private string setIp(string ip, int netmask, string gateway)
        {
            string cmdFormat = $"netsh interface ipv4 set address name={this.CommandContext.Interface} source=static {ip}/{netmask} gateway={gateway}";
            CmdUtil.RunCmd(cmdFormat);
            return null;
        }
        /// <summary>
        /// 显示ip信息
        /// </summary>
        /// <returns></returns>
        private string showIp()
        {
            Interface inter = NetworkUtil.GetWorkInterface(this.CommandContext.Interface);
            if(inter != null)
            {
                return DisplayUtil.displayInterface(inter);
            }
            else
            {
                return $"接口不存在: {this.CommandContext.Interface}";
            }
        }


        public void IpDhcp()
        {
            string cmdFormat = $"netsh interface ipv4 set address name={this.CommandContext.Interface} source=dhcp";
            CmdUtil.RunCmd(cmdFormat);
        }
        public void IpDns()
        {
            var dns = this.CommandContext.InputCommandParams["dns"];
            string cmdFormat = $"netsh int ipv4 set dns name=loopback static {dns} primary";
            CmdUtil.RunCmd(cmdFormat);
        }
    }
}
